import type { Ref } from "vue";
import { ref, reactive, watch, unref } from "vue";

export function userTable<
  R extends { list: any; total: any },
  P extends object
>(
  //接口API的回调函数是它的返回类型
  requestApi: (data: P) => PromiseResType<R>,
  queryParams: RefTypeable<P>
) {
  let tableData: Ref<R["list"]> = ref([]);
  const pageination = reactive({
    currentPage: 1,
    pageSize: 10,
    small: false,
    total: 0,
    background: true,
  });
  const quert = {} as P;
  watch(
    () => queryParams,
    (val, oldValue) => {
      console.log(val);
      for (let key in val) {
        quert[key] = unref(val[key]) as P[Extract<keyof P, string>]; //P[keyword] | P[pageNum] | P[pageSize]
      }
    },
    { deep: true }
  );
  async function fetchData() {
    //发送请求获取用户列表
    let adminlists = await requestApi({
      pageNum: pageination.currentPage,
      pageSize: pageination.pageSize,
      ...quert,
    });
    if (adminlists.code === 200) {
      tableData.value = adminlists.data.list;
      pageination.total = adminlists.data.total;
    }
  }
  fetchData();

  function handleSizeChange() {
    fetchData();
  }

  function handleCurrentChange() {
    fetchData();
  }
  return {
    tableData,
    pageination,
    handleSizeChange,
    handleCurrentChange,
    fetchData,
  };
}
